import array
import math


starting_color = None
color_names = []

snapshot_pixel_size = 8
color_rgb_chunks = {}

palette_size = (4,20)




def _make_spectrum_rgb():
  "Creates a list of (r,g,b) triplets for colors in a spectrum from red to violet"

  corners = [(1,0,0), (1,1,0), (0,1,0), (0,1,1), (0,0,1), (1,0,1), (1,0,0)]

  ranges = {
    (0,0): [0x00] * 4,
    (1,1): [0xff] * 4,
    (0,1): [0x00, 0x66, 0x99, 0xff],
    (1,0): [0xff, 0x99, 0x66, 0x00]
  }

  result = []
  for (start, end) in zip(corners[:-1], corners[1:]):
    ranges_rgb = [ ranges[i] for i in zip(start, end)]
    result.extend(zip(*ranges_rgb)[0:-1])
  return [x for x in result if x!=(0x00,0xff,0x66)] 


def _init_colors():

  def add_color(red, green, blue):
    name = '%02x%02x%02x' % (red, green, blue)
    color_names.append(name)
    color_rgb_chunks[name] = array.array('B', (red,green,blue) * snapshot_pixel_size)

  brightness_scale = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff]

  def scale_down(value, brightness):
    for index in xrange(0, len(brightness_scale)):
      if value == brightness_scale[index]:
        new_index = index * brightness / 6
        return brightness_scale[new_index]
    raise ValueException

  def scale_up(value, brightness):
    for index in xrange(0, len(brightness_scale)):
      if value == brightness_scale[index]:
        new_index = 5 - int(math.ceil((5 - index) * brightness / 6.0))
        return brightness_scale[new_index]
    raise ValueException

  def add_grey(v):
    add_color(v,v,v)

  lo = 0x00
  hi = 0x33

  add_grey(0x00)
  add_grey(0xff)
  add_color(hi,hi,lo)
  add_color(hi,lo,hi)

  add_grey(0x33)
  add_grey(0xcc)
  add_color(hi,lo,lo)
  add_color(lo,lo,hi)

  add_grey(0x66)
  add_grey(0x99)
  add_color(lo,hi,lo)
  add_color(lo,hi,hi)

  for (r,g,b) in _make_spectrum_rgb():
    add_color(scale_up(r,3), scale_up(g,3), scale_up(b,3))
    for brite in [6,5,4]:
      add_color(scale_down(r,brite), scale_down(g,brite), scale_down(b,brite))
      
  for i in xrange(0, len(color_names)):
    if color_names[i] == '0000ff':
      global starting_color
      starting_color = i
      

_init_colors()
